<?php

namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\Log;

class QueryListener
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
    }

    /**
     * Handle the event.
     */
    public function handle(QueryExecuted $event): void
    {
        if (config('app.sql_record')) {
            try {
                $sql = str_replace('?', '%s', $event->sql);
                array_walk($event->bindings, function (&$val, $key): void {
                    $val = \is_int($val) ? $val : "'{$val}'";
                });
                $log = vsprintf($sql, $event->bindings);
                // 执行时间
                $time = $event->time ?? 0.00;

                Log::info(sprintf(' [execute time:%d] ', $time) . $log);
            } catch (\Throwable $e) {
                Log::warning(sprintf('SQL 记录异常，异常信息: %s，sql: %s', $e->getMessage(), json_encode($event, JSON_UNESCAPED_UNICODE)));
            }
        }
    }
}
